import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/components/calendar_btn_icon.dart';
import 'package:share_fit/app/components/date_type_bar.dart';
import 'package:share_fit/app/components/table_calendar_dialog.dart';
import 'package:share_fit/app/controllers/home/exercise_records/components/exercise_records_title.dart';
import 'package:share_fit/app/controllers/home/exercise_records/model/exercise_type.dart' as workout_type;
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/date_type_enum.dart';
import 'package:share_fit/app/models/home/workout_model.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'logic.dart';

class ExerciseRecordsPage extends StatelessWidget {
  ExerciseRecordsPage({super.key});

  final logic = Get.find<ExerciseRecordsLogic>();
  final state = Get.find<ExerciseRecordsLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: BackBtnIcon(onTap: () => logic.goBack()),
        centerTitle: true,
        // title: ExerciseRecordsTitle(),
        title: Text(LocaleKeys.exercise_records_all.ts),
        actions: [
          GetBuilder<ExerciseRecordsLogic>(
            id: 'calendar_btn_icon',
            builder: (ctrl) {
              return ctrl.state.selectedDateType == DateType.day
                  ? CalendarBtnIcon(
                      calenderDay: ctrl.state.selectedDate,
                      onTap: () => _showDatePicker(context),
                    )
                  : Container();
            },
          ),
        ],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: ListView(
          children: [
            SizedBox(height: 59.h),
            GetBuilder<ExerciseRecordsLogic>(
              id: 'date_type_bar',
              builder: (ctrl) => DateTypeBar(
                initIndex: ctrl.state.dateTypeBarIndex,
                onSelectChanged: (index, dateType) => ctrl.changeDateType(selectedIndex: index, type: dateType),
              ),
            ),
            _buildExerciseSummary(),
            GetBuilder<ExerciseRecordsLogic>(
              id: 'date_type_container',
              builder: (ctrl) => ctrl.state.selectedDateType == DateType.day
                  ? Container(height: 30.h)
                  : Container(
                      margin: EdgeInsets.symmetric(horizontal: 40.w),
                      height: 120.h,
                      alignment: Alignment.center,
                      child: ListView.builder(
                        itemCount: ctrl.state.dates.length,
                        shrinkWrap: true,
                        scrollDirection: Axis.horizontal,
                        physics: const AlwaysScrollableScrollPhysics(),
                        itemBuilder: (context, index) => TextButton(
                          style: ButtonStyle(
                            // shape: MaterialStateProperty.all(CircleBorder()),
                            minimumSize: MaterialStateProperty.all(Size(90.w, 40.h)),
                            visualDensity: VisualDensity.compact,
                            padding: MaterialStateProperty.all(EdgeInsets.symmetric(horizontal: 20.w)),
                          ),
                          onPressed: () => ctrl.changeDate(logic.state.dates[index]),
                          child: Text(
                            ctrl.state.selectedDateType == DateType.week
                                ? DateFormat.E(Get.locale?.languageCode).format(ctrl.state.dates[index])
                                : DateFormat('MM/dd').format(ctrl.state.dates[index]),
                            style: TextStyle(color: Colors.black.withOpacity(0.7)),
                          ),
                        ),
                      ),
                    ),
            ),
            SizedBox(height: 30.h),
            GetBuilder<ExerciseRecordsLogic>(
              id: 'workout_list',
              builder: (ctrl) => state.workoutSummary.summaryList.isNotEmpty ? _buildHasRecordsContainer() : _buildNoRecordsContainer(),
            ),
          ],
        ),
      ),
    );
  }

  _buildHasRecordsContainer() {
    return Column(
      children: [
        _buildExerciseRecordsItem(),
        SizedBox(height: 60.h),
      ],
    );
  }

  _buildNoRecordsContainer() {
    return Container(
      height: Get.height - 950.h,
      padding: EdgeInsets.only(top: 600.h),
      child: Column(
        children: [
          Image.asset('assets/images/home/empty.png', width: 350.w, height: 350.h),
          Text(LocaleKeys.exercise_no_records_text.ts, style: TextStyle(fontSize: 48.sp)),
        ],
      ),
    );
  }

  Widget _buildExerciseSummary() {
    return GetBuilder<ExerciseRecordsLogic>(
      id: 'workout_summary',
      builder: (ctrl) => Container(
        alignment: Alignment.center,
        margin: EdgeInsets.symmetric(vertical: 40.h),
        child: RichText(
          text: TextSpan(children: [
            TextSpan(
              text: '${ctrl.state.workoutSummary.totalTimes}',
              style: TextStyle(fontSize: 82.sp, color: Colors.black, fontWeight: FontWeight.bold),
            ),
            const TextSpan(text: ' '),
            TextSpan(
              text: LocaleKeys.exercise_session_text.ts,
              style: TextStyle(fontSize: 42.sp, color: ColorConst.secondaryFontColor),
            ),
          ]),
        ),
      ),
    );
  }

  Widget _buildExerciseRecordsItem() {
    return ListView.separated(
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemCount: state.workoutSummary.summaryList.length,
      itemBuilder: (context, index) => Container(
        decoration: BoxDecoration(color: Colors.white70.withOpacity(1), borderRadius: BorderRadius.circular(40.r)),
        child: Theme(
          data: ThemeData(
            dividerColor: Colors.transparent,
            splashColor: Colors.transparent,
            expansionTileTheme: const ExpansionTileThemeData(
              backgroundColor: Colors.transparent,
              collapsedBackgroundColor: Colors.transparent,
            ),
          ),
          child: ExpansionTile(
            initiallyExpanded: true,
            title: Padding(
              padding: EdgeInsets.only(bottom: 20.h),
              child: Text(state.workoutSummary.summaryList[index].getDateText, style: TextStyle(fontSize: 48.sp)),
            ),
            children: state.workoutSummary.summaryList[index].workouts.map((workout) => _generateRecordItem(workout)).toList(),
          ),
        ),
      ),
      separatorBuilder: (context, index) => SizedBox(height: 30.h),
    );
  }

  /// 生成 ExpansionTile 下的 ListView 的单个组件
  Widget _generateRecordItem(WorkoutModel rec) {
    String summary = '';
    String paceText = '${LocaleKeys.exercise_burn_calories_text.ts} ${rec.calories?.toInt()} ${LocaleKeys.thermal_unit_kcal.ts}';
    String img = 'assets/images/sports/icon_sports_calorie.png';
    if (workout_type.Type.hasDistanceSports(rec.sportsType!)) {
      summary = rec.distanceFormat();
      img = 'assets/images/home/timer.png';
      paceText = rec.getPaceText;
    }

    /// 使用该组件可以使宽度撑满
    return FractionallySizedBox(
      widthFactor: 1,
      child: ListTile(
        onTap: () => logic.goToExerciseDetailPage(rec),
        titleAlignment: ListTileTitleAlignment.titleHeight,
        leading: Image.asset(
          rec.sportTypeImg,
          width: 90.w,
          height: 90.w,
          color: ColorConst.activeColor,
          fit: BoxFit.cover,
        ),
        title: Padding(
          padding: EdgeInsets.only(bottom: 20.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            textBaseline: TextBaseline.alphabetic,
            children: [
              Text('${rec.transformTypeText} $summary', style: TextStyle(fontSize: 48.sp)),
              Baseline(
                baseline: 18,
                baselineType: TextBaseline.alphabetic,
                child: Text('${rec.HMText}', style: TextStyle(fontSize: 40.sp)),
              ),
            ],
          ),
        ),
        subtitle: Row(
          children: [
            Text('${rec.durationText}'),
            SizedBox(width: 30.w),
            Image.asset(img, width: 40.w, height: 40.w),
            SizedBox(width: 30.w),
            // 如果是有距离的运动，显示配速
            Text(paceText)
          ],
        ),
      ),
    );
  }

  _showDatePicker(BuildContext context) {
    Get.dialog(
      TableCalendarDialog(
        onEvenLoad: (day) => logic.onCalendarEventLoad(day),
      ),
      barrierColor: Colors.black.withOpacity(.8),
    ).then((value) => logic.datePicker(value));
  }
}
